package com.novoda.runbuddy.util;

public class DateUtils {

	static final int	FEBRUARY		= 1;
	static final int	DaysInMonth[]	= { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

	public static int calcFirstOfMonth(int year, int month) {
		int firstDay;
		int i;

		if (year < 1582) {
			return (-1);
		}

		if ((month < 0) || (month > 11)) {
			return (-1);
		}

		firstDay = CalcJanuaryFirst(year);

		for (i = 0; i < month; i++) {
			firstDay += DaysInMonth[i];
		}

		if ((month > FEBRUARY) && IsLeapYear(year)) {
			firstDay++;
		}

		return (firstDay % 7);
	}

	public static int CalcJanuaryFirst(int year) {
		if (year < 1582) {
			return (-1);
		}

		return ((5 + (year - 1582) + CalcLeapYears(year)) % 7);
	}

	public static int CalcLeapYears(int year) {
		int leapYears;
		int hundreds;
		int fourHundreds;

		if (year < 1582) {
			return (-1);
		}

		leapYears = (year - 1581) / 4;

		hundreds = (year - 1501) / 100;
		leapYears -= hundreds;

		fourHundreds = (year - 1201) / 400;
		leapYears += fourHundreds;

		return (leapYears);
	}

	public static boolean IsLeapYear(int year) {
		if ((year % 100) == 0) {
			return ((year % 400) == 0);
		}

		return ((year % 4) == 0);
	}
}
